package utils.file;

import java.io.*;

/**
 * @author ZH
 * 文件读写工具类
 */
public class ReadWriteUtil {
    public static boolean write(String content,String path){
        //将写入转化为流的形式
        try {
            BufferedWriter bw = new BufferedWriter(new FileWriter(path));
            String[] split = content.split("\n");
            //一次写一行
            for (String s : split) {
                bw.write(s);
                bw.newLine(); //换行用
            }
            //关闭流
            bw.close();
            System.out.println("写入成功");
            return true;
        }catch (IOException e){
            e.printStackTrace();
            return false;
        }
    }

    public static StringBuffer readFile(String filePath) {
        StringBuffer fileBody = new StringBuffer();
        try {
            File file = new File(filePath);
            if(file.isFile() && file.exists()) {
                InputStreamReader isr = new InputStreamReader(new FileInputStream(file), "utf-8");
                BufferedReader br = new BufferedReader(isr);
                String lineTxt = null;
                while ((lineTxt = br.readLine()) != null) {
                    fileBody.append(lineTxt).append("\n");
                }
                br.close();
                return fileBody;
            } else {
                return new StringBuffer("文件不存在!");
            }
        } catch (Exception e) {
            return new StringBuffer("文件读取错误!");
        }
    }
}
